package com.didi.virtualapk;

import android.Manifest;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.didi.virtualapk.internal.LoadedPlugin;
import com.didi.virtualapk.internal.PluginContentResolver;
import com.didi.virtualapk.pluginlib.IMyInterface;
import com.didi.virtualapk.pluginlib.Manager;
import com.didi.virtualapk.pluginlib.UserInfo;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE_STORAGE = 20171222;

    private static final String TAG = "MainActivity";
    ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            IMyInterface a = (IMyInterface) service;
            int result = a.getCount();
            Toast.makeText(MainActivity.this, "onServiceConnected:" + String.valueOf(result), Toast.LENGTH_SHORT).show();
            Log.e(TAG, String.valueOf(result));
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d(TAG, "onServiceDisconnected");
        }
    };
    private boolean isBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn).setOnClickListener(v -> startActivity());
        findViewById(R.id.btn_startService).setOnClickListener(v -> startService());
        findViewById(R.id.btn_bindService).setOnClickListener(v -> bindService());
        findViewById(R.id.btn_unbindService).setOnClickListener(v -> unbindService());
        findViewById(R.id.btn_stopService).setOnClickListener(v -> stopService());
        findViewById(R.id.btn_cpInsert).setOnClickListener(v -> cpInsert());
        findViewById(R.id.btn_sendBroadcastReceiver).setOnClickListener(v -> sendBroadcastReceiver());

        if (hasPermission()) {
            Log.d(TAG, "loadPlugin");
            this.loadPlugin(this);
        } else {
            requestPermission();
        }
    }

    public void startActivity() {
        final String pkg = "com.didi.virtualapk.demo";
        if (PluginManager.getInstance(this).getLoadedPlugin(pkg) == null) {
            Toast.makeText(this, "plugin [com.didi.virtualapk.demo] not loaded", Toast.LENGTH_SHORT).show();
            return;
        }
        String age = ((EditText) findViewById(R.id.et_age)).getText().toString();
        UserInfo info = new UserInfo();
        info.setUserAge(age);
        Manager.initUserInfo(info);

        Intent intent = new Intent();
        intent.setClassName(MainActivity.this, "com.didi.virtualapk.demo.MainActivity");
        startActivity(intent);
    }

    private void startService() {
        Intent intent = new Intent();
        intent.setClassName(MainActivity.this, "com.didi.virtualapk.demo.PluginService");
        startService(intent);
    }

    private void bindService() {
        Intent intent = new Intent();
        intent.setClassName(MainActivity.this, "com.didi.virtualapk.demo.PluginService");
        isBound = bindService(intent, conn, Service.BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (isBound) {
            unbindService(conn);
            isBound = false;
        }
    }

    private void stopService() {
        Intent intent = new Intent();
        intent.setClassName(MainActivity.this, "com.didi.virtualapk.demo.PluginService");
        stopService(intent);
    }

    private void cpInsert() {
        final String pkg = "com.didi.virtualapk.demo";
        LoadedPlugin plugin = PluginManager.getInstance(this).getLoadedPlugin(pkg);
        Uri cpUri = Uri.parse("content://com.didi.virtualapk.demo.Lilee");
        cpUri = PluginContentResolver.wrapperUri(plugin, cpUri);
        Integer count = getContentResolver().delete(cpUri, "where", null);
        Toast.makeText(this, String.valueOf(count), Toast.LENGTH_SHORT).show();
    }

    private void sendBroadcastReceiver() {
        sendBroadcast(new Intent("plugin_receiver_one"));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PERMISSION_REQUEST_CODE_STORAGE == requestCode) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                requestPermission();
            } else {
                this.loadPlugin(this);
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    private boolean hasPermission() {
        Log.d(TAG, "hasPermission");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    private void requestPermission() {
        Log.d(TAG, "requestPermission");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE_STORAGE);
        }
    }

    private void loadPlugin(Context base) {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "sdcard was NOT MOUNTED!", Toast.LENGTH_SHORT).show();
        }
        PluginManager pluginManager = PluginManager.getInstance(base);
        File apk = new File(Environment.getExternalStorageDirectory(), "VirtualPlugin.apk");
        if (apk.exists()) {
            try {
                pluginManager.loadPlugin(apk);
                Log.i(TAG, "Loaded plugin from apk: " + apk);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                File file = new File(base.getFilesDir(), "VirtualPlugin.apk");
                java.io.InputStream inputStream = base.getAssets().open("VirtualPlugin.apk", 2);
                java.io.FileOutputStream outputStream = new java.io.FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;

                while ((len = inputStream.read(buf)) > 0) {
                    outputStream.write(buf, 0, len);
                }

                outputStream.close();
                inputStream.close();
                pluginManager.loadPlugin(file);
                Log.i(TAG, "Loaded plugin from assets: " + file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
